package org.example.service.authorization.user;

import com.bianmaba.commons.data.jpa.domain.request.Condition;
import com.bianmaba.spring.security.basic.details.CurrentUserDetails;
import com.bianmaba.spring.security.basic.details.UserDetailsServiceImpl;
import org.example.bean.entity.authorization.Role;
import org.example.bean.entity.authorization.User;
import org.example.service.authorization.role.IRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CustomUserDetailsService extends UserDetailsServiceImpl {
    private static final Logger LOG = LoggerFactory.getLogger(CustomUserDetailsService.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    public CustomUserDetailsService() {
        LOG.info("加载自定义UserDetailService：" + CustomUserDetailsService.class.getName());
    }

    @Override
    public CurrentUserDetails findUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user != null) {
            List<Role> roles = roleService.queryToList(Condition.of("users.id", user.getId()));
            List<GrantedAuthority> grantedAuthorities = grantedAuthoritiesByEntitys(roles);
            boolean enabled = user.getEnabled();
            boolean accountNonExpired = user.getAccountExpiringDate().getTime() > System.currentTimeMillis();
            boolean credentialsNonExpired = user.getCredentialsExpiringDate().getTime() > System.currentTimeMillis();
            boolean accountNonLocked = !user.getLocked();
            CurrentUserDetails.UserExtendedInfos infos = new CurrentUserDetails.UserExtendedInfos(user.getId(), user.getName(), user.getUsername(), user.getEmail());

            CurrentUserDetails userDetails = new CurrentUserDetails(user.getUsername(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities, infos);
            return userDetails;
        }
        CurrentUserDetails userDetails = super.findUserByUsername(username);
        return userDetails;
    }

    private List<GrantedAuthority> grantedAuthoritiesByEntitys(List<Role> roles) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(0);
        for (Role role : roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        return grantedAuthorities;
    }
}
